package com.jeeplus.test.jlnu.graduationInfo.controller;


import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.ImportFailLog;
import com.jeeplus.test.jlnu.graduationInfo.domain.entity.NewGraduationInfo;
import com.jeeplus.test.jlnu.graduationInfo.domain.vo.NewGraduationInfoReqVo;
import com.jeeplus.test.jlnu.graduationInfo.service.NewGraduationInfoService;
import com.jeeplus.test.tools.resp.R;
import com.jeeplus.test.tools.utils.MinioUtil;
import io.minio.StatObjectResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Api(tags = "毕业信息")
@RestController
@Slf4j
@RequestMapping("/graduationInfoModule")
public class NewGraduationInfoController {

    @Autowired
    private NewGraduationInfoService graduationInfoService;

    @Autowired
    private MinioUtil minioUtil;


    @ApiOperation("毕业信息分页查询")
    @GetMapping("/page")
    public Page<NewGraduationInfoReqVo> getGraduationInfoPage(NewGraduationInfoReqVo newGraduationInfo, @RequestParam(defaultValue = "1") int pageNum,
                                                           @RequestParam(defaultValue = "10") int pageSize) {
        Page<NewGraduationInfoReqVo> page = new Page<>(pageNum, pageSize);
        Page<NewGraduationInfoReqVo> pageResult = graduationInfoService.getGraduationInfoPage(newGraduationInfo, page);
        return pageResult;
    }


    @ApiOperation("毕业信息模板下载")
    @PostMapping("/graduationTemplate")
    public ResponseEntity<byte[]> graduationTemplate(@RequestBody List<String> ids){
        return graduationInfoService.graduationTemplate(ids);
    }


    @ApiOperation("毕业信息重新导入（只修改教学档案,同时生成导入记录）")
    @PostMapping("/importTecData")
    public R importTecData(@RequestParam("file") MultipartFile file) {
        return graduationInfoService.importGraduationData(file);
    }


    @ApiOperation("毕业信息批量修改")
    @PostMapping("/batchUpdate")
    public R batchUpadte(@RequestBody NewGraduationInfo graduationInfo){
        if (graduationInfo == null || graduationInfo.getStudentIds() == null || graduationInfo.getStudentIds().isEmpty()) {
            return R.error("9999","参数为空");
        }
        graduationInfoService.updateByIdBatch(graduationInfo.getStudentIds(), graduationInfo);
        return R.suc("成功");


    }


    @ApiOperation("批量提交接口")
    @PostMapping("/approval")
    public R approval(@RequestBody List<String> ids) {
        graduationInfoService.approval("2",ids);
        return R.suc();
    }

    @ApiOperation("毕业信息查询")
    @GetMapping("/getGraduationInfo")
    public R getGraduationInfo(@RequestParam String studentId) {
        NewGraduationInfo newGraduationInfo = graduationInfoService.selectByStudentId(studentId);
        if(newGraduationInfo == null){
            return R.error("9999","数据为空");
        }
        return R.suc(newGraduationInfo);
    }


    @ApiOperation("导入记录分页查询")
    @GetMapping("/getImportDataPage")
    public R<Page<ImportFailLog>> getImportDataPage(
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String fileName) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = startTime != null ? sdf.parse(startTime) : null;
        Date endDate = endTime != null ? sdf.parse(endTime) : null;
        Page<ImportFailLog> importDataPage = graduationInfoService.getImportDataPage(pageNum, pageSize, startDate, endDate, fileName);
        return R.suc(importDataPage);
    }



    @GetMapping("/downloadTemplate")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        // 使用 ClassPathResource 从 resources 目录读取文件
        Resource resource = new ClassPathResource("static/毕业信息模板.xlsx");

        // 获取输入流
        InputStream inputStream = resource.getInputStream();

        // 将输入流转换为字节数组
        byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);

        // 设置 HTTP 响应头，指示文件下载
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=import_template.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(fileData.length) // 使用字节数组的长度
                .body(fileData);
    }



    //生成 PDF 预览图片
    @GetMapping("/generatePreviewUrl")
    @ResponseBody
    public R generatePreviewUrl(@RequestParam("bucket") String bucket,@RequestParam("objectName") String objectName) throws Exception {
        // 参数校验
        if (StringUtils.isBlank(bucket) || StringUtils.isBlank(objectName)) {
            return R.error("9999", "参数[bucket]或[objectName]不能为空");
        }

        try (InputStream pdfStream = minioUtil.getObject(bucket, objectName);
             PDDocument document = PDDocument.load(pdfStream)) {

            // 1. 验证文件类型
            StatObjectResponse metadata = minioUtil.getMetaData(bucket, objectName);
            if (!"application/pdf".equals(metadata.contentType())) {
                return R.error("9999", "非PDF文件，预览失败");
            }

            // 2. 渲染 PDF 第一页为图片
            PDFRenderer renderer = new PDFRenderer(document);
            BufferedImage image = renderer.renderImageWithDPI(0, 150); // 第 0 页，指定 DPI

            // 3. 转换为 Base64（或上传到 MinIO 返回 URL）
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", baos);
            String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());

            // 直接返回 Base64 数据（适合小图）
            return R.suc("data:image/png;base64," + base64Image);

            // 上传图片到 MinIO 并返回 URL（适合大图）
            // String imageName = "preview/" + UUID.randomUUID() + ".png";
            // minioUtil.uploadFile("preview-bucket", imageName, baos.toByteArray());
            // String imageUrl = minioUtil.getPresignedObjectUrl("preview-bucket", imageName, 3600);
            // return R.suc(imageUrl);

        } catch (Exception e) {
            log.error("PDF预览图生成失败 | bucket={}, objectName={} | 错误详情:", bucket, objectName, e);
            return R.error("999", "预览图生成失败: " + e.getMessage());
        }
    }


    //批量移交
    @ApiOperation("批量移交")
    @PostMapping("/batchUpdateGraduation")
    public R batchUpdateGraduation(@RequestBody NewGraduationInfoReqVo newGraduationInfoReqVo) {
        // 参数校验
        if (CollectionUtils.isEmpty(newGraduationInfoReqVo.getIds())) {
            return R.error("9999", "请选择需要移交的数据");
        }
        graduationInfoService.batchUpdateGraduation(newGraduationInfoReqVo);
        return R.suc();
    }


}
